//
//  AddUserVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/20.
//

import UIKit

class AddUserVC: BaseVC {
    var userInfo = DMCCUser()
    var desc = String()
    init(userInfo: DMCCUser = DMCCUser()) {
        super.init(nibName: nil, bundle: nil)
        self.userInfo = userInfo
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setup()
        
        self.updateUserinfo()
    }
    
    func updateUserinfo () {
        
        if (gosnUser.getUserInfo(self.userInfo.userId) != nil) {
            
        }else{
            Task {
                let user = await gosnUser.fetchUserInfo(self.userInfo.userId)
                
                await MainActor.run {
                    if user != nil {
                        self.userInfo = user!
                        GK_main_async_safe {
                            self.tableView.reloadData()
                        }
                    }
                }
                
                
            }
        }
    }
    
    @objc func tfTarget(tf:UITextField) {
        desc = tf.text!
    }

    func setup () {
        tableView.register(UINib(nibName: "UserCell", bundle: nil), forCellReuseIdentifier: "UserCell")
        tableView.register(UINib(nibName: "LogoutCell", bundle: nil), forCellReuseIdentifier: "LogoutCell")
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 120
        }
        
        return 60
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
//    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        let view = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 10))
//        view.backgroundColor = UIColor.lightGray
//        return view
//    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            
        if indexPath.section == 0  {
            let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
            cell.setUserInfo(userInfo: self.userInfo)
            cell.imgWidth.constant = 70
            cell.imgHeight.constant = 70
            return cell
        }else if (indexPath.section == 1) {
            let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
            cell.contentView.backgroundColor = UIColor.clear
            let tf = UITextField(frame: CGRectMake(20, 10, kScreenWidth - 40, 40))
            tf.placeholder = "附言"
            tf.addTarget(self, action: #selector(tfTarget), for: .editingChanged)
            cell.contentView.addSubview(tf)
            return cell
        }

        let cell = tableView.dequeueReusableCell(withIdentifier: "LogoutCell", for: indexPath) as! LogoutCell
        cell.titleLab.text = "添加好友"
        cell.titleLab.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
        cell.titleLab.textColor = UIColor.MainColor
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
        if (indexPath.section == 0  && indexPath.row == 0) {
            if userInfo.getNft()!.count > 0 {
                self.navigationController?.pushViewController(PrivacyWebVC(string: userInfo.getNft()!), animated: true)
            }
            
        }
        if indexPath.section == 2 {
            sendFriendRequest()
        }
    }
    
    func sendFriendRequest() {
        MHAlert.showLoading()
        
        let myinfo = gosnUser.getUserInfoDefault(gosnUser.myId())
        let alias = myinfo.getAlias()
        
        Task{
            let res = await gosnFriend.inviteFriend(self.userInfo.userId, desc)
            
            if res{
                let textContent = OsnTextMessageContent()
                textContent.data = desc.count > 0 ? desc : "你好，我是\(alias)"
                
                let (msg,error) = await gosnMessage.sendMessage(self.userInfo.userId, textContent)
                if error == nil {
                    geventService.post(.kUpDateConversation, "")
                }
            }
            
            
            await MainActor.run {
                if res{
                    MHAlert.showMessage(KLocalizedString("AlertLoadSuccess"))
                    DispatchQueue.main.async {
                        self.navigationController?.popToRootViewController(animated: true)
                    }
                }else{
                    MHAlert.showMessage(KLocalizedString("GroupMessageTimeOut"))
                }
            }
        }

    }
    
    
    deinit {
        
    }
}
